from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required


# 首页视图：演示登录后访问的页面（最基础）
@login_required(login_url='accounts:login')
def home(request):
    # 中文注释：将当前用户名传给模板用于展示
    return render(request, 'accounts/home.html', {'user': request.user})


# 注册视图：接收 POST 表单并创建用户
def register(request):
    # 中文注释：仅实现最基础的验证逻辑（非生产级）
    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
        password2 = request.POST.get('password2', '').strip()

        if not username or not password:
            messages.error(request, '用户名和密码不能为空')
        elif password != password2:
            messages.error(request, '两次输入的密码不一致')
        elif User.objects.filter(username=username).exists():
            messages.error(request, '该用户名已被注册')
        else:
            # 创建用户并保存到数据库
            User.objects.create_user(username=username, password=password)
            messages.success(request, '注册成功，请登录')
            return redirect('accounts:login')

    return render(request, 'accounts/register.html')


# 登录视图：授权并跳转到首页
def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
        user = authenticate(request, username=username, password=password)
        if user is not None:
            auth_login(request, user)
            return redirect('accounts:home')
        else:
            messages.error(request, '用户名或密码错误')

    return render(request, 'accounts/login.html')


# 登出视图：退出登录并跳回登录页
def logout_view(request):
    auth_logout(request)
    return redirect('accounts:login')
